package bu.met.cs664;

import java.util.Scanner;

public class TicTacToe {

	/**
	 * Play Tic Tac Toe
	 * 
	 * @param	args	N/A
	 */
	public static void main(String[] args) {
		Board board = new Board();
		
		printBoard(board);
		Player playerX, playerO;
		
		char inChoice = readPlayerChoice();
		if (inChoice == 'O') {
			playerO = new HumanPlayer(Player.PLAYER_X);
			playerX = new NewellAndSimonPlayer(Player.PLAYER_O);
		} else {
			playerX = new HumanPlayer(Player.PLAYER_X);
			playerO = new NewellAndSimonPlayer(Player.PLAYER_O);
		}
		
		int turn = 1;
		int xGoesFirst = 1; // Set to 1 for X to take the first turn, 0 for O.
		
		while (!board.isGameOver(playerX, playerO)) {
			Player currentPlayer;
					
			// Alternate whose turn it is.
			if ((turn % 2) == xGoesFirst) {
				currentPlayer = playerX;
			} else {
				currentPlayer = playerO;
			}
			
			System.out.println("Turn " + turn);
			
			board.select(currentPlayer, currentPlayer.nextMove(board));
			
			printBoard(board);
			turn++;
		}
		
		Player winner = null;
		
		if (board.won(playerX)) {
			winner = playerX;
		} else if (board.won(playerO)) {
			winner = playerO;
		}
		
		if (winner != null) {
			System.out.println("Player " + winner + " wins!");
		} else {
			System.out.println("Game ends in a tie.");
		}
	}

	private static char readPlayerChoice() {
		System.out.println("Would you like to play as X or O?");
		Scanner in = new Scanner(System.in);
		String inChoiceString = in.nextLine();
		char inChoice = ((inChoiceString.length() > 0)? inChoiceString.toUpperCase().charAt(0) : 'X');
		return inChoice;
	}
	
	public static void printBoard(Board board) {
		String verticalSeparator = " | ", horizontalSeparator = "\n---+---+---\n";
		StringBuilder boardBuilder = new StringBuilder();
		char[] boardState = board.getCurrentState();
		for (int i = 0; i < boardState.length; i++) {
			boardBuilder.append(boardState[i]);
			if (i%3 == 0){
				boardBuilder.append(" ");
			}
			if (i%3 == 2 && i != 8) {
				boardBuilder.append(horizontalSeparator);
			} else if (i != 8) {
				boardBuilder.append(verticalSeparator);
			}			
		}
		
		System.out.println(boardBuilder.toString());
	}

}
